package com.example.usermanagement.controller;

import com.example.usermanagement.entity.User;
import com.example.usermanagement.service.UserService;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/user")
public class UserController {

    @Autowired
    private UserService userService;

    /**
     * 新增用户信息
     */
    @PostMapping
    public User insert(@RequestBody User user) {
        return userService.insert(user);
    }

    /**
     * 修改用户信息
     */
    @PutMapping
    public User update(@RequestBody User user) {
        return userService.update(user);
    }

    /**
     * 根据ID删除用户信息
     */
    @DeleteMapping("/{id}")
    public boolean delete(@PathVariable Integer id) {
        return userService.deleteById(id);
    }

    /**
     * 批量删除用户信息
     */
    @DeleteMapping("/batch")
    public boolean deleteBatch(@RequestBody List<Integer> ids) {
        return userService.deleteBatch(ids);
    }

    /**
     * The following implementations are for GET requests
     */
    
    /**
     * 查询用户详情
     */
    @GetMapping("/{id}")
    public User getById(@PathVariable Integer id) {
        return userService.getById(id);
    }

    /**
     * 查询全部用户信息
     */
    @GetMapping
    public List<User> getAll() {
        return userService.getAll();
    }

    /**
     * 排序查询
     */
    @GetMapping("/orderBy")
    public List<User> getAllOrderBy(@RequestParam String field, @RequestParam String order) {
        return userService.getAllOrderBy(field, order);
    }

    /**
     * 单条件查询
     */
    @GetMapping("/condition")
    public List<User> getByOneCondition(
            @RequestParam(required = false) String field,
            @RequestParam(required = false) String value) {
        Map<String, Object> condition = new HashMap<>();
        condition.put(field, value);
        return userService.getByCondition(condition);
    }

    /**
     * 多条件查询
     */
    @GetMapping("/conditions")
    public List<User> getByConditions(@RequestParam Map<String, Object> params) {
        return userService.getByCondition(params);
    }

    /**
     * 模糊查询
     */
    @GetMapping("/search")
    public List<User> search(@RequestParam String keyword) {
        return userService.getByLike(keyword);
    }

    /**
     * 分页模糊查询
     */
    @GetMapping("/page")
    public PageInfo<User> page(
            @RequestParam(defaultValue = "") String keyword,
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "10") Integer pageSize) {
        return userService.getPageByLike(keyword, pageNum, pageSize);
    }
} 